﻿/*******************************************************************************************
 * Copyright (c) 2006-2009 Alex Robson, Rob Simmons, Craig Israel, and Rachel Twyford
 *
 * Use of this software in any form requires that you have both 
 * read and agreed to the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions: 
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the 
 * documentation and/or other materials provided with the distribution.
 * Neither the name of Nvigorate nor the names of its contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Nvigorate.Extensions;

namespace Nvigorate.Common.Reflection
{
    public sealed partial class Reflector
    {
        internal static object CallMethod(object target, Type type, string methodName, object[] arguments, Type[] genericArguments)
        {
            var fullName = type.FullName;
            var isStatic = target == null;

            MethodInfo methodInfo = arguments.Length > 0 ?
                GetMethodInfo(type, methodName, arguments, isStatic, SearchHierarchy).FirstOrDefault() :
                GetMethodInfo(type, methodName, SearchHierarchy).FirstOrDefault();

            if (methodInfo == null)
            {
                throw new ReflectorException(
                    "Reflector could not invoke the target method {0}.{1} because it does not exist.",
                    fullName, methodName);
            }

            try
            {
                methodInfo = genericArguments != null ?
                    methodInfo.MakeGenericMethod(genericArguments) : methodInfo;


                var expectedTypes = methodInfo.GetParameters().Select(p => p.ParameterType).ToArray();
                var parameters = ConvertParameters(arguments, expectedTypes);
                return methodInfo.Invoke(target, parameters);
            }
            catch (TargetException ex)
            {
                throw new ReflectorException(ex, "The method, {0}.{1} ",
                                             " in is not a valid target. See inner exception for more detail.",
                                             fullName, methodName);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException != null)
                    throw ex.InnerException;
                throw;
            }
            catch (TargetParameterCountException ex)
            {
                throw new ReflectorException(ex, "Wrong number of arguments supplied to, {0}.{1} by Reflector.",
                                             " See inner exception for more detail.",
                                             fullName, methodName);
                throw;
            }
        }

        internal static object[] ConvertParameters(object[] parameters, Type[] targetTypes)
        {
            int index = 0;
            return parameters.Select(p =>
                {
                    var parameterType = targetTypes[index++];
                    if(p == null)
                    {
                        return p;
                    }
                    if(parameterType.IsGenericParameter)
                    {
                        return p;
                    }
                    return TypeCaster.ConvertValue(p, parameterType);
                }).ToArray();
        }

        /// <summary>
        /// Returns a specific field info object from the type
        /// </summary>
        /// <param name="type">The System.Type to search</param>
        /// <param name="memberName">The case sensitive member name</param>
        /// <param name="searchHierarchy">A boolean indicating whether or not to search inherited members</param>
        /// <returns>A list of MethodInfo objects matching the constraints provided</returns>
        internal static List<MemberInfo> GetMemberInfo(Type type, string memberName, bool searchHierarchy)
        {
            List<MemberInfo> memberInfo = new List<MemberInfo>();
            memberInfo.AddRange((IEnumerable<MemberInfo>)type.GetMember(memberName, useFlag));
            memberInfo.AddRange((IEnumerable<MemberInfo>)type.GetMember(memberName, staticFlag));

            return (searchHierarchy && memberInfo.Count <= 0 & type.BaseType != typeof(object))
                       ?
                           GetMemberInfo(type.BaseType, memberName, true)
                       :
                           memberInfo;
        }

        /// <summary>
        /// Returns a list of MemberInfo for members of the type of the specified MemberTypes
        /// </summary>
        /// <param name="type">The System.Type to search</param>
        /// <param name="memberType">A list of member types to search within</param>
        /// <param name="searchHierarchy">A boolean indicating whether or not to search inherited members</param>
        /// <returns>A list of MethodInfo objects matching the constraints provided</returns>
        internal static List<MemberInfo> GetMemberInfo(Type type, MemberTypes memberType, bool searchHierarchy)
        {
            List<MemberInfo> memberInfo = new List<MemberInfo>();
            List<MemberInfo> members = new List<MemberInfo>();

            memberInfo.AddRange((IEnumerable<MemberInfo>)type.GetMembers(useFlag));
            memberInfo.AddRange((IEnumerable<MemberInfo>)type.GetMembers(staticFlag));
            if (searchHierarchy && type.BaseType != typeof(object))
            {
                memberInfo.AddRange(GetMemberInfo(type.BaseType, memberType, true));
            }

            return memberInfo.FindAll(member => member.MemberType == memberType);
        }

        /// <summary>
        /// Returns a list of all MemberInfo for the type
        /// </summary>
        /// <param name="type">The System.Type to search</param>
        /// <param name="searchHierarchy">A boolean indicating whether or not to search inherited members</param>
        /// <returns>A list of MethodInfo objects matching the constraints provided</returns>
        internal static List<MemberInfo> GetMemberInfo(Type type, bool searchHierarchy)
        {
            List<MemberInfo> memberInfo = new List<MemberInfo>();
            memberInfo.AddRange((IEnumerable<MemberInfo>)type.GetMembers(useFlag));
            memberInfo.AddRange((IEnumerable<MemberInfo>)type.GetMembers(staticFlag));

            if (searchHierarchy && type.BaseType != typeof(object))
            {
                memberInfo.AddRange(GetMemberInfo(type.BaseType, true));
            }
            return memberInfo;
        }

        /// <summary>
        /// Return an ordered array of Types for each of the instances in instanceArray.
        /// </summary>
        /// <param name="instanceArray">An array of object instances</param>
        /// <returns>A Type array with the ordered Types of the objects</returns>
        internal static Type[] GetTypeArray(object[] instanceArray)
        {
            return instanceArray.ToList().Select(o => o.GetType()).ToArray();
        }

        internal static Type LoadTypeByName(string typeName)
        {
            List<Assembly> currentAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

            Predicate<Assembly> match = a => typeName.Contains(a.GetName().Name);
            Type targetType = null;
            foreach (var assembly in currentAssemblies.FindAll(match))
            {
                targetType = assembly.GetType(typeName);
                if (targetType != null)
                    return targetType;
            }

            if (targetType == null)
            {
                List<AssemblyName> referencedAssemblies =
                    currentAssemblies
                        .Select(a => a.GetReferencedAssemblies())
                        .SelectMany(a => a)
                        .Where(a => typeName.Contains(a.Name))
                        .ToList();

                referencedAssemblies.ForEach(r =>
                {
                    var assembly = Assembly.Load(r);
                    Type foundType = assembly.GetType(typeName);
                    if (foundType != null)
                        targetType = foundType;
                });
            }

            return targetType;
        }

        internal static Type LoadTypeByName(string typeName, string assemblyName)
        {
            var currentAssemblies =
                AppDomain
                    .CurrentDomain
                    .GetAssemblies()
                    .ToList();

            var matchingAssemblies =
                currentAssemblies
                    .Where(a => a.GetName().Name == assemblyName);

            Type targetType = null;
            foreach (var assembly in matchingAssemblies)
            {
                targetType = assembly.GetType(typeName);
                if (targetType != null)
                    return targetType;
            }

            if (targetType == null)
            {
                List<AssemblyName> referencedAssemblies =
                    currentAssemblies
                        .Select(a => a.GetReferencedAssemblies())
                        .SelectMany(a => a)
                        .Where(a => a.Name == assemblyName)
                        .ToList();

                referencedAssemblies.ForEach(r =>
                {
                    var assembly = Assembly.Load(r);
                    Type foundType = assembly.GetType(typeName);
                    if (foundType != null)
                        targetType = foundType;
                });
            }

            return targetType;
        }

        internal static IEnumerable<Type> ProjectParameterTypes(MethodInfo methodInfo)
        {
            var parameters = methodInfo.GetParameters();
            //if (methodInfo.IsGenericMethod)
            //{
            //    return parameters.Select(p =>
            //                                       p.ParameterType.IsGenericParameter
            //                                           ? p.ParameterType
            //                                           : p.ParameterType);
            //}
            //else
            //{
                return parameters.Select(p => p.ParameterType);
            //}
        }
    }
}
